import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import {
    Switch,
    Row,
    Col,
    Card,
    Progress,
    Statistic,
    Typography,
    Space,
    Button,
    message,
    Tooltip,
    Tag,
    Modal,
    Popconfirm,
    Spin,
} from "antd";
import {
    DeploymentUnitOutlined,
    PlayCircleOutlined,
    CloudOutlined,
    DashboardOutlined,
    DatabaseOutlined,
    ProductOutlined,
    CloudUploadOutlined,
    BarsOutlined,
    SyncOutlined,
    InfoCircleOutlined,
    PoweroffOutlined,
    BranchesOutlined,
} from "@ant-design/icons";
import { postBindInfo } from "@/services/nodes/api";
import styles from "./Localhost.module.css";
import {
    postReaload,
    postBasicInfo,
    postUnBindNode,
} from "@/services/nodes/api";
import UnOnline from "./UnOnline";

interface NodeItem {
    nodeID: string;
}

const RestNode: React.FC<{ nodeID: string }> = ({ nodeID }) => {
    const { Title, Text } = Typography;
    const [nodeStatus, setNodeStatus] = useState(false);
    const [apiError, setApiError] = useState(false); // 新增状态用于跟踪API错误
    const [loading, setLoading] = useState(true); // 新增loading状态
    const [time, setTime] = useState("");
    const [space, setSpace] = useState("");
    const [load, setLoad] = useState({
        cpuLoad: 0,
        memoryUsage: 0,
        diskUsage: 0,
    });
    const [hostingCount, setHostingCount] = useState<any>({
        all: 0,
        live: 0,
        deploy: 0,
    });
    const [systemInfo, setSystemInfo] = useState<any>([]);
    const [compileStatus, setCompileStatus] = useState<any>([]);
    const initNodeId = () => { 
        const param = new URLSearchParams(window.location.search);
        const temp_id = param.get("node_id")
        if (temp_id === null) {
            return "0";
        } else {
            return temp_id;
        }
    };
    const selectNodeID = initNodeId()
    // 初始化数据
    useEffect(() => {
        const initBasicInfo = async () => {
            await postBasicInfo(selectNodeID)
                .then((res: any) => {
                    // 检查API返回的status字段
                    if (res.status === "error") {
                        setApiError(true);
                        setNodeStatus(false);
                        setLoading(false);
                        return;
                    }
                    
                    setApiError(false);
                    setNodeStatus(true);
                    const data = res.message;
                    setTime(data.realtime);
                    setSpace(data.fm_occ_space);
                    
                    // 检查 hosting_count 数据结构是否正常
                    if (data.hosting_count && typeof data.hosting_count === 'object' &&
                        'all' in data.hosting_count && 'live' in data.hosting_count && 'deploy' in data.hosting_count) {
                        setHostingCount({
                            all: data.hosting_count.all || 0,
                            live: data.hosting_count.live || 0,
                            deploy: data.hosting_count.deploy || 0,
                        });
                    } else {
                        // 数据结构不正常，设置错误状态
                        setHostingCount(null as any); // 使用null表示数据错误
                        message.error("托管应用统计数据结构异常");
                    }
                    
                    setSystemInfo(data.system_info);
                    setCompileStatus(data.compile_status);
                    setLoading(false);
                })
                .catch((err: any) => {
                    message.error(err.message);
                    setLoading(false);
                });
        };

        // 初始化时获取数据
        initBasicInfo();

        // 每30秒请求一次基础信息（除系统负载外的所有信息）
        const basicInfoTimer = setInterval(() => {
            initBasicInfo();
        }, 30000);

        // 每秒更新时间（本地计算）
        const timer = setInterval(() => {
            setTime((prevTime) => {
                if (prevTime) {
                    // 尝试解析时间字符串
                    const date = new Date(prevTime);
                    // 检查日期是否有效
                    if (!isNaN(date.getTime())) {
                        date.setSeconds(date.getSeconds() + 1);
                        // 格式化为API返回的时间格式: yyyy/MM/dd HH:mm:ss
                        const year = date.getFullYear();
                        const month = String(date.getMonth() + 1).padStart(
                            2,
                            "0",
                        );
                        const day = String(date.getDate()).padStart(2, "0");
                        const hours = String(date.getHours()).padStart(2, "0");
                        const minutes = String(date.getMinutes()).padStart(
                            2,
                            "0",
                        );
                        const seconds = String(date.getSeconds()).padStart(
                            2,
                            "0",
                        );
                        return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
                    }
                }
                return prevTime;
            });
        }, 1000);

        // 获取系统负载信息
        const initReaload = async () => {
            await postReaload(selectNodeID)
                .then((res: any) => {
                    setNodeStatus(true);
                    setLoad({
                        cpuLoad: res.message.cpu,
                        memoryUsage: res.message.mem,
                        diskUsage: res.message.disk,
                    });
                })
                .catch((err: any) => {
                    message.error(err.message);
                });
        };

        // 每5秒请求一次系统负载信息
        const loadTimer = setInterval(() => {
            initReaload();
        }, 5000);

        // 初始化时获取数据
        initReaload();

        // 清理定时器
        return () => {
            clearInterval(timer);
            clearInterval(loadTimer);
            clearInterval(basicInfoTimer);
        };
    }, []);

    const [autoStartEnabled, setAutoStartEnabled] = useState<boolean>(false);
    const navigate = useNavigate();

    const UnBindNode = async () => {
        return await postUnBindNode({ node_id: nodeID }, navigate)
            .then((res: any) => {
                message.info(res.message);
                navigate("/nodes");
                setTimeout(() => {
                    window.location.reload();
                }, 100);
            })
            .catch((err: any) => {
                message.error(err.message);
            });
    };
    if (loading) {
        return (
            <div style={{ 
                display: 'flex', 
                justifyContent: 'center', 
                alignItems: 'center', 
                height: '60vh',
                flexDirection: 'column'
            }}>
                <Spin size="large" />
                <div style={{ marginTop: 16, fontSize: 16, color: '#666' }}>
                    数据加载中...
                </div>
            </div>
        );
    }
    
    if (apiError) {
        return (
            <div style={{ 
                display: 'flex', 
                justifyContent: 'center', 
                alignItems: 'center', 
                height: '60vh'
            }}>
                <div style={{ textAlign: 'center' }}>
                    <div style={{ fontSize: 24, color: '#f5222d', marginBottom: 8 }}>
                        节点不在线
                    </div>
                    <div style={{ fontSize: 16, color: '#888' }}>
                        无法连接到该节点，请检查节点状态
                    </div>
                </div>
            </div>
        );
    }
    
    if (!nodeStatus) {
        return (
            <div style={{ 
                display: 'flex', 
                justifyContent: 'center', 
                alignItems: 'center', 
                height: '60vh'
            }}>
                <div style={{ textAlign: 'center' }}>
                    <div style={{ fontSize: 24, color: '#f5222d', marginBottom: 8 }}>
                        节点不在线
                    </div>
                    <div style={{ fontSize: 16, color: '#888' }}>
                        无法连接到该节点，请检查节点状态
                    </div>
                </div>
            </div>
        );
    } else {

        return (
            <div
                className={styles.container}
                style={{
                    padding: "24px",
                    maxHeight: "85vh",
                    overflowY: "auto",
                    position: "relative",
                }}
            >
                <Card
                    title={
                        <Space>
                            <BarsOutlined />
                            <span>主要信息</span>
                        </Space>
                    }
                    extra={
    
                        <Popconfirm
                            title="确定要解除绑定此节点吗？"
                            onConfirm={UnBindNode}
                            okText="确定"
                            cancelText="取消"
                            // 位置在左边
                            okButtonProps={{
                                danger: true,
                            }}
                        >
                            <Button
                                type="primary"
                                danger
                            >
                                解绑
                            </Button>
                        </Popconfirm>
                    }
                    style={{ marginBottom: "20px" }}
                >
                    <Row gutter={[16, 16]}>
                        <Col xs={24} sm={8} md={8}>
                            <Card size="small">
                                <Statistic title="服务器时间" value={time} />
                            </Card>
                        </Col>
                        <Col xs={24} sm={8} md={8}>
                            <Card size="small">
                                <Statistic
                                    title="渔翁及数据占用磁盘空间"
                                    value={space}
                                />
                            </Card>
                        </Col>
                        <Col xs={24} sm={8} md={8}>
                            <Card size="small">
                                <Statistic
                                    title="开机自启动"
                                    value=""
                                    valueStyle={{
                                        visibility: "hidden",
                                        height: 0,
                                        margin: 0,
                                        padding: 0,
                                    }}
                                />
                                <div style={{ marginBottom: "13px" }}></div>
                                <Tooltip title={"功能开发中..."}>
                                    <Switch
                                        disabled
                                        checked={autoStartEnabled}
                                        onChange={setAutoStartEnabled}
                                        checkedChildren="启用"
                                        unCheckedChildren="未启用"
                                    />
                                </Tooltip>
                            </Card>
                        </Col>
                    </Row>
                </Card>
    
                {/* 系统负载区域 */}
                <Card
                    title={
                        <Space>
                            <CloudOutlined />
                            <span>系统负载</span>
                        </Space>
                    }
                    style={{ marginBottom: "20px" }}
                >
                    <Row gutter={[16, 16]}>
                        <Col xs={24} sm={12} md={8}>
                            <Card size="small">
                                <Statistic
                                    title="CPU使用率"
                                    value={load.cpuLoad}
                                    suffix="%"
                                    prefix={<DeploymentUnitOutlined />}
                                />
                                <Progress
                                    percent={load.cpuLoad}
                                    status="active"
                                    strokeColor={"#5352ed"}
                                />
                            </Card>
                        </Col>
                        <Col xs={24} sm={12} md={8}>
                            <Card size="small">
                                <Statistic
                                    title="内存使用率"
                                    value={load.memoryUsage}
                                    suffix="%"
                                    prefix={<DatabaseOutlined />}
                                />
                                <Progress
                                    percent={load.memoryUsage}
                                    status="active"
                                    strokeColor={"#5352ed"}
                                />
                            </Card>
                        </Col>
                        <Col xs={24} sm={12} md={8}>
                            <Card size="small">
                                <Statistic
                                    title="根目录分区使用率"
                                    value={load.diskUsage}
                                    suffix="%"
                                    prefix={<DatabaseOutlined />}
                                />
                                <Progress
                                    percent={load.diskUsage}
                                    status="active"
                                    strokeColor={"#5352ed"}
                                />
                            </Card>
                        </Col>
                    </Row>
                </Card>
                <Card
                    title={
                        <Space>
                            <ProductOutlined />
                            <span>托管应用统计</span>
                        </Space>
                    }
                    // extra={
                    //     <>
                    //         <Button style={{marginRight:"15px"}}>导入</Button>
                    //         <Button>导出</Button>
                    //     </>
                    // }
                    style={{ marginBottom: "20px" }}
                >
                    {hostingCount === null ? (
                        <div style={{ textAlign: "center", padding: "20px" }}>
                            <Text type="danger">数据加载错误</Text>
                            <div>托管应用统计数据结构异常</div>
                        </div>
                    ) : (
                        <Row gutter={[16, 16]}>
                            <Col xs={24} sm={8} md={8}>
                                <Card size="small">
                                    <Statistic
                                        title="应用总数"
                                        value={hostingCount.all}
                                        prefix={<DeploymentUnitOutlined />}
                                    />
                                </Card>
                            </Col>
                            <Col xs={24} sm={8} md={8}>
                                <Card size="small">
                                    <Statistic
                                        title="运行中应用"
                                        value={hostingCount.live}
                                        prefix={<PlayCircleOutlined />}
                                        valueStyle={{ color: "#2ed573" }}
                                    />
                                </Card>
                            </Col>
                            <Col xs={24} sm={8} md={8}>
                                <Card size="small">
                                    <Statistic
                                        title="发布总数"
                                        value={hostingCount.deploy}
                                        prefix={<CloudUploadOutlined />}
                                    // valueStyle={{ color: "#3f8600" }}
                                    />
                                </Card>
                            </Col>
                        </Row>
                    )}
                </Card>
                <Card
                    title={
                        <Space>
                            <SyncOutlined />
                            <span>自编译软件状态</span>
                            <Tooltip title="区别于其他已安装软件，为避免发生冲突，不建议脱离渔翁单独使用。">
                                <Button
                                    type="text"
                                    icon={
                                        <InfoCircleOutlined
                                            style={{ fontSize: "16px" }}
                                        />
                                    }
                                    style={{
                                        display: "flex",
                                        alignItems: "center",
                                    }}
                                />
                            </Tooltip>
                        </Space>
                    }
                    style={{ marginBottom: "20px" }}
                >
                    <Row gutter={[16, 16]}>
                        {compileStatus.map((service: any, index: any) => (
                            <Col xs={24} sm={12} md={8} key={index}>
                                <Card size="small">
                                    <Statistic
                                        title={service.name}
                                        value=""
                                        valueStyle={{
                                            visibility: "hidden",
                                            height: 0,
                                            margin: 0,
                                            padding: 0,
                                        }}
                                    />
                                    <div style={{ marginBottom: "13px" }}></div>
                                    {service.status === "True" ? (
                                        <Tag color="success">{"编译成功"}</Tag>
                                    ) : (
                                        <Tag color="error">{"编译失败"}</Tag>
                                    )}
                                </Card>
                            </Col>
                        ))}
                    </Row>
                </Card>
    
                {/* 操作系统信息区域 */}
                <Card
                    title={
                        <Space>
                            <DashboardOutlined />
                            <span>操作系统信息</span>
                        </Space>
                    }
                >
                    <Row gutter={[16, 16]}>
                        {systemInfo.map((env: any, index: any) => (
                            <Col xs={24} sm={12} md={12} key={index}>
                                <div
                                    style={{
                                        display: "flex",
                                        justifyContent: "space-between",
                                    }}
                                >
                                    <Text strong>{env.name}:</Text>
                                    <Text>{env.value}</Text>
                                </div>
                            </Col>
                        ))}
                    </Row>
                </Card>
            </div>
        );
    }
};

export default RestNode;
